﻿@{
    ViewBag.MainMenu = "Settings";
    ViewBag.LeftMenu = "Material";

    ViewBag.Title = "图文消息";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<link rel="stylesheet" type="text/css" href="/Scripts/wangEditor/css/wangEditor.min.css">
<script type="text/javascript" src='/Scripts/wangEditor/js/wangEditor.min.js'></script>

<style>
    .wangEditor-container .wangEditor-txt p,
    .wangEditor-container .wangEditor-txt h1,
    .wangEditor-container .wangEditor-txt h2,
    .wangEditor-container .wangEditor-txt h3,
    .wangEditor-container .wangEditor-txt h4,
    .wangEditor-container .wangEditor-txt h5 {
        margin: 0px 0;
        line-height: 1.8;
    }
</style>

<style type="text/css">
    .divImageMaterialContainer {
        width: 170px;
        background-color: #FFF;
    }

    .tableImageMaterialContainer {
        width: 100%;
        border-collapse: collapse;
        border: solid #E7E7EB;
        border-width: 1px 0 0 1px;
    }

        .tableImageMaterialContainer td {
            border: 1px solid #E7E7EB;
        }

    .divArticleMaterialContainer {
        background-color: #FFF;
        font-size: 13px;
    }

    .tableArticleMaterialContainer {
        width: 100%;
        border-collapse: collapse;
        border: solid #E7E7EB;
        border-width: 1px 0 0 1px;
    }

        .tableArticleMaterialContainer td {
            border: 1px solid #E7E7EB;
        }

    .tableNoBorder {
        border: 0px;
    }

        .tableNoBorder td {
            border: 0px;
        }

    .divFirstArticleTitle {
        position: absolute;
        line-height: 24px;
        padding-left: 7px;
        vertical-align: middle;
        left: 0px;
        right: 0px;
        bottom: 0px;
        height: 24px;
        background-color: #000000;
        color: white;
        filter: alpha(opacity=70);
        -moz-opacity: 0.7;
        -khtml-opacity: 0.7;
        opacity: 0.7;
    }

    .divArticleFirstItem {
        cursor: pointer;
        border: 2px solid #FFF;
        position: relative;
        height: 100px;
    }

        .divArticleFirstItem:hover {
            border: 2px solid #393;
        }

    .divArticleItem {
        cursor: pointer;
        margin-top: 10px;
        margin-left: 5px;
        margin-right: 5px;
        border: 2px solid #FFF;
    }

        .divArticleItem:hover {
            border: 2px solid #393;
        }

    .divArticleItemActive {
        border: 2px solid skyblue;
    }
</style>

<script language="javascript">

    var _mode = "create";//modify
    var _id;

    //文章列表，WeixinAddArticleMaterialArgs
    var _articleList;
    var _currentArticleIndex = -1;

    var _validator;

    //富文本编辑器
    var _editor;

    $(document).ready(function () {
        _validator = $("#form").validate({
            ignore: "", // 开启hidden验证， 1.9版本后默认关闭
            onfocusout: false,
            onkeyup: false,
            showErrors: showValidationErrors,
            rules: {
                "txtName": "required",
                "txtTitle": "required",
                "hiddenMediaId": "required"
            },
            messages: {
                "txtName": "请输入素材名称；",
                "txtTitle": "请输入标题；",
                "hiddenMediaId": "请选择封面图片；"
            }
        });

        //_editor = $('#txtContent').wangEditor({
        //    'menuConfig': [
        //     ['viewSourceCode'],
        //        ['bold', 'underline', 'italic', 'foreColor', 'backgroundColor', 'strikethrough'],
        //        ['blockquote', 'fontFamily', 'fontSize', 'setHead', 'list', 'justify'],
        //        ['createLink', 'unLink', 'insertTable'],
        //        ['insertLocation'],
        //        ['undo', 'redo', 'fullScreen']
        //    ]
        //});
        _editor = new wangEditor('divContentEditor');
        _editor.config.menus = [
        'source',
        '|', 'bold', 'underline', 'italic', 'strikethrough', 'eraser', 'forecolor', 'bgcolor',
        '|', 'quote', 'fontfamily', 'fontsize', 'head', 'unorderlist', 'orderlist', 'alignleft', 'aligncenter', 'alignright',
        '|', 'link', 'unlink', 'table',
        '|', 'undo', 'redo', 'fullscreen'
        ];
        _editor.create();


        _id = getQueryString("id");
        if (_id == undefined || _id == "") {
            //如果是新建默认就要有一篇
            addArticle();
        }
        else {
            loadData(_id);
        }

    });

    function loadData(id) {
        _mode = "modify";

        $("#spanTitle").html("修改图文素材");
        // $("#btnRemove").show();

        var loadLayerIndex = layer.load(0, {
            shade: [0.2, '#fff']
        });

        $.ajax({
            url: "/Api/Material/GetArticleMaterial?id=" + id,
            type: "POST",
            dataType: "json",
            success: function (data, status, jqXHR) {
                layer.close(loadLayerIndex);
                if (data.Success) {
                    _articleList = data.Data;
                    //  $("#txtId").val(pointCommodity.Id);
                    $("#txtName").val(_articleList.name);

                    //if (_articleList.weixinStatus != 2)
                    //{
                    //    $("#divFailedMessage").show();
                    //}

                    if (_articleList.weixinStatus == 0) {
                        $("#divRemoveCurrent").show();
                        $("#btnSaveAndPublish").show();
                        $("#btnSaveAndPublish").removeAttr("disabled");
                        $("#btnSaveAndPublish2").show();
                        $("#btnSaveAndPublish2").removeAttr("disabled");
                        $("#spanPublish").html("尚未发布");
                    }
                    else {
                        $("#divRemoveCurrent").hide();
                        $("#btnSaveAndPublish").hide();
                        $("#btnSaveAndPublish2").hide();
                        $("#spanPublish").html("已发布");
                    }

                    switchArticle(0);

                } else {
                    layerAlert(data.Message);
                }
            },
            error: function (xmlHttpRequest) {
                layer.close(loadLayerIndex);
                alert("Error: " + xmlHttpRequest.status);
            }
        });
    }

    //添加一篇文章并使之选中
    function addArticle() {
        if (_articleList == null)
            _articleList = new Object();

        if (_articleList.articles == undefined || _articleList.articles == null) {
            _articleList.articles = new Array();
        }

        //Infrastructure.ArticleMaterialItemEntity
        var article = new Object();
        article.title = "请输入标题";
        article.thumb_media_id = "";
        article.show_cover_pic = 0;
        article.author = "请输入作者";
        article.digest = "";
        article.content = "";
        article.url = "";
        article.content_source_url = "";

        article.thumbUrl = "";
        article.thumbName = "";

        article.imgMappingList = new Array();

        _articleList.articles[_articleList.articles.length] = article;

        switchArticle(_articleList.articles.length - 1);
    }

    function showArticleList() {
        if (_articleList.articles == undefined || _articleList.articles == null || _articleList.articles.length == 0) {
            document.getElementById('divArticleList').innerHTML = "";
            return;
        }

        var gettpl = document.getElementById('articleListTemplate').innerHTML;
        laytpl(gettpl).render(_articleList.articles, function (html) {
            document.getElementById('divArticleList').innerHTML = html;
        });
    }

    //选中并加载指定的文章
    function switchArticle(index) {
        //切换前保存当前的文章
        saveCurrentArticle();

        _currentArticleIndex = index;

        showArticleList();

        var article = _articleList.articles[index];

        $("#txtTitle").val(article.title);
        $("#txtAuthor").val(article.author);
        $("#txtContentSourceUrl").val(article.content_source_url);
        if (article.show_cover_pic == 1) {
            $("#chkShowCoverPic").attr("checked", "checked");
        }
        else {
            $("#chkShowCoverPic").removeAttr("checked");
        }
        $("#txtDigest").val(article.digest);
        $("#hiddenMediaId").val(article.thumb_media_id);

        _editor.$txt.html(article.content);

        showMaterialImage(article);
    }

    //保存当前文章
    function saveCurrentArticle() {
        if (_currentArticleIndex < 0)
            return;

        var article = _articleList.articles[_currentArticleIndex];
        if (article == null)
            return;

        article.title = $("#txtTitle").val();
        article.author = $("#txtAuthor").val();
        article.content_source_url = $("#txtContentSourceUrl").val();
        article.show_cover_pic = $("#chkShowCoverPic").is(":checked") ? 1 : 0;
        article.digest = $("#txtDigest").val();

        article.content = _editor.$txt.html();
    }

    function showMaterialImageSelect() {
        //alert(0);
        layer.open({
            type: 2,
            area: ['760px', '450px'], //宽高
            closeBtn: false,
            title: "",
            shift: _layerShift,
            content: '/Material/ImageSelect'
        });
    }

    function __selectMaterialImageResult(image, layerIndex) {
        if (layerIndex != undefined && layerIndex != null) {
            layer.close(layerIndex);
        }

        var article = _articleList.articles[_currentArticleIndex];

        article.thumb_media_id = image.MediaId;
        article.thumbUrl = image.Url;
        article.thumbName = image.Name;

        //showMaterialImage(article);
        switchArticle(_currentArticleIndex);
    }

    function showMaterialImage(article) {
        if (article.thumb_media_id != undefined && article.thumb_media_id != null && article.thumb_media_id != "") {
            $("#divMaterialImage_Select").hide();
            $("#divMaterialImage_Image").show();

            var gettpl = document.getElementById('tableMaterialImageTemplate').innerHTML;
            laytpl(gettpl).render(article, function (html) {
                document.getElementById('divMaterialImage_Image').innerHTML = html;
            });
        } else {
            $("#divMaterialImage_Select").show();
            $("#divMaterialImage_Image").hide();
        }
    }

    function removeMaterialImage() {
        var article = _articleList.articles[_currentArticleIndex];

        article.thumb_media_id = "";
        article.thumbUrl = "";
        article.thumbName = "";

        //showMaterialImage(article);
        switchArticle(_currentArticleIndex);
    }

    function validateArticle() {
        for (var i = 0; i < _articleList.articles.length; i++) {
            var article = _articleList.articles[i];
            if (article.title == "" || article.thumb_media_id == "") {
                switchArticle(i);
                return false;
            }
        }

        return true;
    }

    function save(callback) {
        saveCurrentArticle();

        if (validateArticle() == false) {
            if (_validator.form() == false) {
                return;
            }
        }

        _articleList.name = $("#txtName").val();

        var url = "/Api/Material/AddArticleMaterial";

        if (_articleList.id != undefined && _articleList.id != null && _articleList.id != "") {
            url = "/Api/Material/UpdateArticleMaterial";
        }

        var loadLayerIndex = layer.load(0, {
            shade: [0.2, '#fff']
        });

        $.ajax({
            url: url,
            type: "POST",
            dataType: "json",
            data: JSON.stringify(_articleList),
            success: function (data, status, jqXHR) {
                // alert(data);
                layer.close(loadLayerIndex);
                if (data.Success) {
                    if (_mode == "create") {
                        layerAlert("保存成功。", function () {
                            var loadLayerIndex = layer.load(0, {
                                shade: [0.2, '#fff']
                            });

                            window.location.href = "/Material/ArticleEdit?id=" + data.Data.Id;
                        });
                    } else {
                        if (callback != undefined && callback != null) {
                            callback();
                        }
                        else {
                            layerAlert("保存成功。");
                        }
                    }
                } else {
                    layerAlert(data.Message, function () {
                        if (_mode == "create" && data.Data.Id != null && data.Data.Id != "") {
                            window.location.href = "/Material/ArticleEdit?id=" + data.Data.Id;
                        }
                    });
                }
            },
            error: function (xmlHttpRequest) {
                layer.close(loadLayerIndex);
                alert("Error: " + xmlHttpRequest.status);
            }
        });
    }

    function moveUp() {
        if (_currentArticleIndex <= 0)
            return;

        saveCurrentArticle();

        var currentArticle = _articleList.articles[_currentArticleIndex];

        _articleList.articles.splice(_currentArticleIndex, 1);

        var newIndex = _currentArticleIndex - 1;

        _articleList.articles.splice(newIndex, 0, currentArticle);

        _currentArticleIndex = -1;

        switchArticle(newIndex);
    }

    function moveDown() {
        if (_currentArticleIndex >= _articleList.articles.length - 1)
            return;

        saveCurrentArticle();

        var currentArticle = _articleList.articles[_currentArticleIndex];

        _articleList.articles.splice(_currentArticleIndex, 1);

        var newIndex = _currentArticleIndex + 1;

        _articleList.articles.splice(newIndex, 0, currentArticle);

        _currentArticleIndex = -1;

        switchArticle(newIndex);
    }

    function removeCurrent() {
        if (_currentArticleIndex < 0)
            return;

        if (_articleList.articles.length == 1)
            return;

        _articleList.articles.splice(_currentArticleIndex, 1);

        if (_articleList.articles.length == 0) {
            addArticle();
        }

        _currentArticleIndex = -1;
        switchArticle(0);
    }

    function uploadFile() {

        fileUploadArgs = new Object();
        fileUploadArgs.uploadMethod = "UploadToWeixinImg";
        fileUploadArgs.getUploadResultApi = "/Api/Settings/GetUploadToWeixinImgResult?fileId={0}";

        __showFileUpload(getUploadResult, fileUploadArgs);
    }

    function getUploadResult(fileServiceAddress, result) {

       // alert(JSON.stringify(result));
        //当前文章
        var article = _articleList.articles[_currentArticleIndex];
        if (article == null)
            return;

        if (article.imgMappingList == undefined || article.imgMappingList == null) {
            article.imgMappingList = new Array();
        }

        var url = fileServiceAddress + result.Data.StoreFilePath;

        var materialImgMapping = new Object();
        materialImgMapping.Id = result.Data.Id;
        materialImgMapping.FileUrl = url;
        materialImgMapping.WeixinUrl = result.Data.WeixinUrl;

        article.imgMappingList[article.imgMappingList.length] = materialImgMapping;

        _editor.$txt.append("<img src='" + url + "' style='max-width:100%' />");
    }

    function publish() {
        var confirmLayerIndex = layer.confirm("是否确认发布该素材到微信后台？<br/>注意：受限于微信接口，图文素材在发布到微信后台之后，您就不可以再添加或删除文章，但是可以对既有文章进行修改。", {
            btn: ['确认', '取消'], //按钮
            shade: [0.4, '#393D49'],
            title: false,
            closeBtn: false,
            shift: _layerShift
        }, function () {
            layer.close(confirmLayerIndex);

            save(doPublish);
        });
    }

    function doPublish() {
        var loadLayerIndex = layer.load(0, {
            shade: [0.2, '#fff']
        });

        $.ajax({
            url: "/Api/Material/PublishArticleMaterial?id=" + _id,
            type: "POST",
            dataType: "json",
            success: function (data, status, jqXHR) {
                layer.close(loadLayerIndex);
                if (data.Success) {
                    layerAlert("发布成功。", function () {
                        var loadLayerIndex = layer.load(0, {
                            shade: [0.2, '#fff']
                        });

                        window.location.href = "/Material/ArticleEdit?id=" + _id;
                    });

                } else {
                    layerAlert(data.Message);
                }
            },
            error: function (xmlHttpRequest) {
                layer.close(loadLayerIndex);
                alert("Error: " + xmlHttpRequest.status);
            }
        });
    }

</script>

<script id="tableMaterialImageTemplate" type="text/html">

    <div class="divImageMaterialContainer">
        <table class="tableImageMaterialContainer">
            <tr>
                <td height="150" align="center"><img style="max-width:166px; max-height:100%" src="{{ d.thumbUrl }}" /></td>
            </tr>
            <tr>
                <td height="30" style="word-wrap: break-word; word-break: break-all; ">
                    <span class="font_gray_15" style="margin-left: 10px; ">{{ d.thumbName }}</span>
                </td>
            </tr>
            <tr>
                <td height="30" valign="middle" bgcolor="#F4F5F9">
                    <div>
                        @*<div style="float: left; margin-left: 10px;">
                                <img src="/Content/Images/ico_edit.jpg" width="20" height="20">
                            </div>*@
                        <div style="float: right; margin-right: 10px;">
                            <img src="/Content/Images/ico_remove.jpg" width="20" height="20" onclick="removeMaterialImage()">
                        </div>
                        <div style="clear: both"></div>
                    </div>
                </td>
            </tr>
        </table>

    </div>

</script>

<script id="articleListTemplate" type="text/html">

    <div class="divArticleMaterialContainer">
        <table class="tableArticleMaterialContainer">
            <tr>
                <td valign="top">
                    <div>
                        <div class="divArticleFirstItem {{# if(_currentArticleIndex == 0){ }}divArticleItemActive{{# } }}"
                             onclick="switchArticle(0)">
                            <div style="position:absolute; left:0px; right:0px; height:100px; overflow:hidden">
                                <img src="{{ d[0].thumbUrl }}" style=" width:100%;">
                            </div>
                            <div class="divFirstArticleTitle">
                                {{ d[0].title }}
                            </div>
                        </div>

                        {{# for(var i = 1, len = d.length; i < len; i++){ }}
                        <div class="divDotLine" style="margin-top:10px;">
                        </div>
                        <div class="divArticleItem  {{# if(_currentArticleIndex == i){ }}divArticleItemActive{{# } }}"
                             onclick="switchArticle({{i}})">
                            <table class="tableNoBorder" width="100%" border="0" cellspacing="0" cellpadding="0">
                                <tr>
                                    <td>{{ d[i].title }}</td>
                                    <td width="75" align="right"><img src="{{ d[i].thumbUrl }}" width="70" height="70"></td>
                                </tr>
                            </table>
                        </div>

                        {{# } }}

                    </div>
                </td>
            </tr>
            {{# if(_articleList.weixinStatus==undefined || _articleList.weixinStatus == 0){ }}
            <tr>
                <td height="50" align="center" valign="middle" bgcolor="#F4F5F9">
                    <div>
                        <a href="javascript:void(0)" onclick="addArticle()">+ 点击添加 </a>
                    </div>
                </td>
            </tr>
            {{# } }}
        </table>
    </div>



</script>

@*<div id="divContentTips">
        配置公众平台账号，才能让你的店铺与微信公众号关联。   <a href="#">查看详细&gt;</a>
    </div>*@

@*<div style=" margin-top:20px;">
        <table width="100%" border="0" cellspacing="0" cellpadding="0">
            <tr>
                <td class="td_ContentTab_active">图文消息</td>
                <td class="td_ContentTab">图片库</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td colspan="3" bgcolor="#EEEEEE" height="2"></td>
            </tr>
        </table>
    </div>*@

<div style="margin-left:20px; margin-right:20px;">
    <div style=" margin-top:15px; ">
        <span id="spanTitle" class="font_black_24">新建图文素材</span>
        <span id="spanPublish" style="color:gray;margin-left:20px;"></span>
        <div style="float:right;margin-left:20px;">
            <input name="btnSaveAndPublish" type="button" class="btn_blue" id="btnSaveAndPublish" value="保存并发布到微信后台" onclick="publish()" disabled />
        </div>
        <div style="float:right">
            <input name="btnSave" type="button" class="btn_blue" id="btnSave" value="保存" onclick="save()" />
        </div>
        <div style="clear:both"></div>
    </div>

    <div style="margin-top:15px; padding-left:20px;padding-top:5px; padding-bottom:5px; border: 1px dotted red; ">
        注意：受限于微信接口，图文素材在发布到微信后台之后，您就不可以再添加或删除素材中的文章，但是可以对既有文章进行修改。
    </div>

    @*<div id="divFailedMessage" style="margin-top:10px; color:red;display:none">
            未能成功同步到微信素材库，请点击“保存”按钮重试。
        </div>*@

    <form id="form">
        <div style="margin-top:20px; padding-left:0px;">
            <table width="100%" border="0" cellpadding="5" cellspacing="0">
                <tr>
                    <td width="120">名称：</td>
                    <td><input id="txtName" name="txtName" type="text" class="input_16" style="width:300px; " maxlength="50" /></td>
                </tr>
            </table>
        </div>

        <div style="margin-top:20px;">
            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                <tr>
                    <td width="260" valign="top">
                        <div id="divArticleList">

                        </div>
                        <div class="divDotBorder_gray" style="margin-top:10px;">
                            <div style="float:left">
                                <a href="javascript:void(0)" onclick="moveUp()">上移</a> <a href="javascript:void(0)" onclick="moveDown()">下移</a>
                            </div>
                            <div id="divRemoveCurrent" style="float:right">
                                <a href="javascript:void(0)" onclick="removeCurrent()">删除</a>
                            </div>
                            <div style="clear:both"></div>
                        </div>
                    </td>
                    <td width="20"></td>
                    <td valign="top">
                        <div>
                            <div>
                                <input id="txtTitle" name="txtTitle" type="text" class="input_16" maxlength="64" />
                            </div>
                            <div class="divDotLine" style="margin-top:10px;">
                            </div>
                            <div>
                                <input id="txtAuthor" name="txtAuthor" type="text" class="input_16" style="margin-top:10px;" maxlength="8" />
                            </div>
                            <div style="margin-top:10px;">
                                <div id="divContentEditor" style='height:300px; '></div>
                            </div>
                            <div>
                                <div style="float:right;">
                                    <input name="btnUpload" type="button" class="btn_white" id="btnUpload" value="上传图片" onclick="uploadFile()" />
                                </div>
                                <div style="clear:both"></div>
                            </div>
                            <div style="margin-top:10px;">
                                原文链接
                            </div>
                            <div style="margin-top:1px;">
                                <input id="txtContentSourceUrl" name="txtContentSourceUrl" type="text" class="input_16" style="margin-top:10px;" maxlength="500" />
                            </div>
                            <div style="margin-top:10px;">
                                <span>封面</span>
                                <span>大图片建议尺寸：900像素 * 500像素</span>
                            </div>
                            <input type="hidden" id="hiddenMediaId" name="hiddenMediaId" />
                            <div id="divMaterialImage_Select" style="margin-top:10px;">
                                <div class="divDotBorder_gray" style="width:150px; height:150px; cursor:pointer" onclick="showMaterialImageSelect()">
                                    <table height="100%" style="vertical-align:middle" width="100%" border="0" align="center" cellpadding="0" cellspacing="0">
                                        <tr>
                                            <td align="center" valign="middle">
                                                <div>
                                                    <img src="/Content/Images/plus.jpg" width="35" height="35">
                                                </div>
                                                <div style="margin-top:10px;">
                                                    从素材库选择
                                                </div>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                            <div id="divMaterialImage_Image">

                            </div>
                            <div style="margin-top:10px;">
                                <input name="" id="chkShowCoverPic" type="checkbox" class="input_checkbox" value="" />
                                <label for="chkShowCoverPic">封面图片显示在正文中</label><span style="margin-left:30px;"></span>
                            </div>
                            <div style="margin-top:10px;">
                                <span>摘要</span>
                                <span>选填，如果不填写会默认抓取正文前54个字</span>
                            </div>
                            <div style="margin-top:10px;">
                                <textarea name="txtDigest" rows="4" class="input_18" id="txtDigest" maxlength="120"></textarea>
                            </div>
                        </div>

                    </td>
                </tr>
            </table>

        </div>
    </form>
</div>

<div style=" margin-top:25px;">
    <div style="float:right;margin-left:20px;">
        <input name="btnSaveAndPublish2" type="button" class="btn_blue" id="btnSaveAndPublish2" value="保存并发布到微信后台" onclick="publish()" disabled />
    </div>
    <div style="float:right">
        <input name="btnSave" type="button" class="btn_blue" id="btnSave" value="保存" onclick="save()" />
    </div>
    <div style="clear:both"></div>
</div>


@Helpers.FileUpload()